<?php

namespace App\ApiBackend;

use App\Http\Controllers\ApiBaseController;
use App\Jobs\AdminLoginLogJob;
use App\Models\AdminModel;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Hash;

/**
 *  登陆
 */
class Login extends ApiBaseController
{

  /**
   * 参数检查
   */
  protected function check(): void
  {
    try {
      request()->validate([
        'username' => 'required',
        'password' => 'required',
      ]);
    } catch (\Exception $exception) {
      $this->result["code"] = 1;
      $this->result["message"] = "预检: " . $exception->getMessage();
    }
  }

  /**
   * 业务主体
   */
  protected function service(): void
  {
    $adminer = AdminModel::where('username', \request('username'))->select([
      "adminId",
      "password",
      "status",
    ])->first();
    if (!$adminer) {
      $this->result["code"] = 1;
      $this->result["message"] = "登陆失败: 账号不存在 ";
      return;
    }
    if ($adminer->status === 0) {
      $this->result["code"] = 1;
      $this->result["message"] = "登陆失败: 账号已禁用 ";
      return;
    }
    if (!Hash::check(\request('password'), $adminer->password)) {
      $this->result["code"] = 1;
      $this->result["message"] = "登陆失败: 用户密码错误 ";
      return;
    }
    //更新最后登录时间
    $lastUsedTime = DB::table('user_token')->where('tokenable_type', 'App\Models\AdminModel')
      ->where('tokenable_id', $adminer->adminId)->value('updated_at');
    if (!empty($lastUsedTime)) {
      DB::table('admin')->where('adminId', $adminer->adminId)->update(['lastLoginTime' => $lastUsedTime]);
    }
    //删除之前token
    $adminer->destroyAuthTokens();
    $this->result['data']['token'] = $adminer->getAuthToken();

    //登录日志
    // $requestLog = [
    //     "ip"=>request()->ip(),
    //     "userAgent"=>request()->header("user-agent"),
    // ];
    // AdminLoginLogJob::dispatch($adminer,(Object)$requestLog);//->onQueue('log');
    return;
  }
}
